AddCSLuaFile("cl_init.lua")
AddCSLuaFile("shared.lua")

include("shared.lua")

ENT.KeyValues = {"Point", "Radius"}

function ENT:Initialize()
	self:SetMoveType(MOVETYPE_NONE)
	self:SetSolid(SOLID_NONE)
	self:DrawShadow(false)

	self:SetRadius(self.Radius or (1024 * SCALE))

	self:SetRadius(self.Radius)

	self:SetTrigger(true)
end

function ENT:SetRadius(radius)
	self.Radius = radius

	self:PhysicsInitSphere(radius)
	self:SetCollisionBounds(Vector(-radius, -radius, -radius), Vector(radius, radius, radius))

	local phys = self:GetPhysicsObject()
	if phys:IsValid() then
		phys:EnableCollisions(false)
		phys:EnableMotion(false)
	end

	self:SetCollisionGroup(COLLISION_GROUP_DEBRIS_TRIGGER)
	self:SetNotSolid(true)
end

function ENT:SetPoint(point)
	self:SetDTInt(0, point)

	pos = self:GetPos()

	GAMEMODE.MaxCheckpoint = math.max(GAMEMODE.MaxCheckpoint, point)
	table.insert(GAMEMODE.Checkpoints, pos)

	gmod.BroadcastLua("GAMEMODE.MaxCheckpoint="..tostring(GAMEMODE.MaxCheckpoint))
	gmod.BroadcastLua("table.insert(GAMEMODE.Checkpoints, Vector("..pos.x..", "..pos.y..", "..pos.z.."))")
end

function ENT:KeyValue(key, value)
	key = string.lower(key)
	if key == "point" then
		self:SetPoint(tonumber(value) or 0)
	elseif key == "radius" then
		self:SetRadius(math.max(1, tonumber(value) or self.Radius))
	end
end

function ENT:Touch(ent)
	if ent.IsHoverGear then
		local owner = ent:GetVehicleOwner()
		if owner:IsValid() and owner:Alive() and owner:Team() == TEAM_RACING and TrueVisible(self:GetPos(), ent:NearestPoint(self:GetPos())) then
			gamemode.Call("PlayerHitCheckpoint", owner, self:GetPoint())
		end
	end
end
